package com.example.maybeaccount;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Mode.Account;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.ItemAdapter;
import com.example.maybeaccount.Mode.ItemManager;
//import com.example.maybeaccount.Mode.SlideRecyclerView;
import com.example.maybeaccount.Mode.SpacesItemDecoration;
import com.example.maybeaccount.Mode.SqliteDB;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import java.util.ArrayList;
import java.util.List;

/** 主活动，即统计界面 */
public class MainActivity extends AppCompatActivity {
    private ArrayList<Item> itemList = new ArrayList<Item>();
    private   int firstFlag = 0;
    private ItemAdapter itemAdapter;
    public ItemManager itemManager;
    private RecyclerView recyclerView;
    private Spinner spinner;
    private String accountName;
    private int countMode = ItemAdapter.MONTH_MODE;
    private boolean isTop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(0x80000000,0x80000000);
        setContentView(R.layout.activity_main);
        Button month = (Button) findViewById(R.id.month);
        //Button createAccount = (Button) findViewById(R.id.year);
        Button year   = findViewById(R.id.year);
        Button credit = findViewById(R.id.credit);
        Button allItemButton = findViewById(R.id.all_item);
        //FloatingActionButton fabMore = (FloatingActionButton)findViewById(R.id.multiple_actions);
        recyclerView = findViewById(R.id.recycler_view);
        final TextView textBalance = (TextView)findViewById(R.id.balance);
        final TextView textIncome = (TextView)findViewById(R.id.income);
        final TextView textExpend = (TextView)findViewById(R.id.expend);
        final com.getbase.floatingactionbutton.FloatingActionButton addItemButton = findViewById(R.id.action_add_item);
        final com.getbase.floatingactionbutton.FloatingActionButton addAccountButton = findViewById(R.id.action_add_account);
        final com.getbase.floatingactionbutton.FloatingActionButton tubiao = findViewById(R.id.action_chart);
        final com.getbase.floatingactionbutton.FloatingActionButton settingButton = findViewById(R.id.action_setting);
        
        FloatingActionsMenu floatingActionsMenu = findViewById(R.id.multiple_actions);
        spinner = (Spinner)findViewById(R.id.account_spinner);

        //****** 新建账户界面 *******
        addAccountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreateAccountDialog dialog2 = new CreateAccountDialog(MainActivity.this, R.style.Theme_AppCompat_Dialog, new CreateAccountDialog.PriorityListener() {
                    @Override
                    public void setAccountData(String name, String category, String amount, String remark) {
                        // 存储新建的用户
                        // Toast.makeText(MainActivity.this,"新建账户的名称为"+name+"，类别为"+category+"，余额为" + amount + "，备注为"+remark,Toast.LENGTH_LONG).show();
                        Account account = new Account(name,category,Double.parseDouble(amount),remark);
                        saveAccount(account);
                    }
                });
                dialog2.show();

                final WindowManager.LayoutParams params = dialog2.getWindow().getAttributes();
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.WRAP_CONTENT;
                dialog2.getWindow().setAttributes(params);
            }
        });

        //****** 图表界面 *******
        tubiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(itemManager == null){
                    Toast.makeText(MainActivity.this,"请先记账", Toast.LENGTH_SHORT).show();
                }else{
                    Intent totubiao = new Intent(MainActivity.this, Chart.class);
                    totubiao.putExtra("itemManager",itemManager);
                    startActivity(totubiao);
                }
            }
        });

        //******* 不统计，所有账单 *******
        allItemButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countMode = ItemAdapter.ALL_MODE;
                setRecyclerView(countMode);
            }
        });

        //******* 按月统计 *******
        month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countMode = ItemAdapter.MONTH_MODE;
                setRecyclerView(countMode);
            }
        });

        //******* 按年统计 **********
        year.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countMode = ItemAdapter.YEAR_MODE;
                setRecyclerView(countMode);
            }
        });

        //******* 显示所有信贷 ******
        credit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countMode = ItemAdapter.CREDIT_MODE;
                setRecyclerView(countMode);
            }
        });

        //****** 记账界面 *******
        
        addItemButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent tojizhang = new Intent(MainActivity.this, AddItem.class);
                startActivity(tojizhang);
            }
        });

        //****** 重置界面（以后改设置）*****
        settingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toSetting = new Intent(MainActivity.this, ActivitySetting.class);
                startActivity(toSetting);
            }
        });


        //设置账户
        setSpinner();

        //数据显示
        final ImageButton switch_eye = findViewById(R.id.switch_eye);
        if( initVisualData()){
            textBalance.setText(itemManager.getAllAmount()+"");
            textExpend.setText(itemManager.getAllExpend()+"");
            textIncome.setText(itemManager.getAllIncome()+"");

            switch_eye.setOnClickListener(new View.OnClickListener() {
                int eye_flag=1;
                @Override
                public void onClick(View v) {
                    if(eye_flag==0){
                        switch_eye.setImageResource(R.drawable.eye);
                        eye_flag=1;
                        textBalance.setText(itemManager.getAllAmount()+"");
                        textExpend.setText(itemManager.getAllExpend()+"");
                        textIncome.setText(itemManager.getAllIncome()+"");
                    }
                    else if(eye_flag==1){
                        switch_eye.setImageResource(R.drawable.closeeye);
                        eye_flag=0;
                        textBalance.setText("**·*");
                        textExpend.setText("**·*");
                        textIncome.setText("**·*");
                    }
                }
            });

        }

        initBroadcast();
    }

    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        //Toast.makeText(getApplicationContext(),"mainAct onResume",Toast.LENGTH_LONG).show();
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(MainActivity.this, Entrance.class);
            intent.putExtra("resume","Main");
            startActivity(intent);

        }else{
            //firstFlag = 1;
            firstFlag = 0;
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        isTop = false;
    }



    /**
     * 重写返回键 直接退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            firstFlag = 1;
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }else {
            // = 1;
        }
        return super.onKeyDown(keyCode,event);

    }

    /*
    @Override
    public void onAttachedToWindow(){
        //this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        super.onAttachedToWindow();
        firstFlag = 1;
    }*/

    /**
     * 保存账户
     * @param account
     * @return
     */
    private boolean saveAccount(Account account){
        int result = SqliteDB.getInstance(getApplicationContext()).saveAccount(account);
        if(result == 1){
            Toast.makeText(getApplicationContext(),"添加账户成功",Toast.LENGTH_LONG).show();
            return true;
        }else if(result == -1){
            Toast.makeText(getApplicationContext(),"账户已存在",Toast.LENGTH_LONG).show();
            return false;
        } else{
            Toast.makeText(getApplicationContext(),"添加账户失败！",Toast.LENGTH_LONG).show();
            return false;
        }
    }

    /**
     * 初始化统计数据
     */
    private boolean initVisualData(){
        //获取所有账单
        itemList = SqliteDB.getInstance(getApplicationContext()).getAllItem();
        if(itemList.isEmpty()){
            return false;
        }else{
            itemManager = new ItemManager();
            itemManager.setItem(itemList);
            itemManager.setAccountList(MainActivity.this);
            //需要先设置为全部账户，用于初始化
            itemManager.chooseAccount("全部账户");
            itemManager.calculateMonthItem();//按月统计
            itemManager.calculateDataAll();
            LinearLayoutManager layoutManager= new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
            setRecyclerView(ItemAdapter.MONTH_MODE);
            //设置各个item之间的间隔
            int space = 8;
            recyclerView.addItemDecoration(new SpacesItemDecoration(space));
            return true;
        }
    }

    /**
     * 控制recyclerView显示的模式
     * @param mode
     */
    private void setRecyclerView(int mode){
        if(itemManager != null){
            switch (mode){
                case ItemAdapter.YEAR_MODE:
                    if(!itemManager.isYearHasBeenCal()){
                        itemManager.calculateYearItem();
                    }
                    itemAdapter = new ItemAdapter(itemManager.getYearItemList(), mode, MainActivity.this);
                    break;
                case ItemAdapter.MONTH_MODE:
                    if(!itemManager.isMonthHasBeenCal()){
                        itemManager.calculateMonthItem();
                    }
                    itemAdapter = new ItemAdapter(itemManager.getMonthItemList(), mode, MainActivity.this);
                    break;
                case ItemAdapter.ACCOUNT_MODE:
                    if(!itemManager.isAccountHasBeenCal()) {
                        itemManager.calculateAccountItem();
                    }
                    itemAdapter = new ItemAdapter(itemManager.getAccountItemList(), mode, MainActivity.this);
                    break;
                case ItemAdapter.ALL_MODE:
                    itemAdapter = new ItemAdapter(itemManager.getAllItemList(), mode, MainActivity.this);
                    break;
                case ItemAdapter.CREDIT_MODE:
                    itemAdapter = new ItemAdapter(itemManager.getCreditItemList(), mode, MainActivity.this);
                    break;
                default:
            }
            recyclerView.setAdapter(itemAdapter);
        }

    }

    /**
     * 设置Spinner
     */
    private void setSpinner(){
        //载入所有账户名
        ArrayList<String> accountNameList = SqliteDB.getInstance(getApplicationContext()).getAllAccountName();
        accountNameList.add(0,"全部账户");
        accountNameList.add(1,"账户统计");
        final String[] accountList = accountNameList.toArray(new String[accountNameList.size()]);
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, accountList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                // 获取到TextView
                TextView tv = (TextView)view;
                // 修改样式属性
                tv.setTextColor(Color.parseColor("#FFFFFF"));
                tv.setTextSize(15f);
                tv.setGravity(Gravity.CENTER);
                accountName = accountList[pos];
                //根据选择设置要显示的内容
                if(accountName == "账户统计"){
                    countMode = ItemAdapter.ACCOUNT_MODE;
                    setRecyclerView(countMode);
                }else if(itemManager != null){
                    itemManager.chooseAccount(accountName);
                    setRecyclerView(countMode);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }

}
